#pragma once

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
#include "log.hpp"

enum
{
    sockerr = 2,
    binderr,
    listenerr,
    connecterr
};

int backlog = 10;

class Sock
{
public:
    Sock(int sockfd = 0)
        : _sockfd(sockfd)
    {
    }

    ~Sock()
    {
    }

    void Socket()
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_sockfd < 0)
        {
            lg(Fatal, "create socket error %d, strerror %s", errno, strerror(errno));
            exit(sockerr);
        }
    }

    void Bind(uint16_t port)
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;
        socklen_t len = sizeof(local);
        if (bind(_sockfd, (const sockaddr *)&local, len) < 0)
        {
            lg(Fatal, "bind error %d, strerror %s", errno, strerror(errno));
            exit(binderr);
        }
    }

    void Listen()
    {
        if (listen(_sockfd, backlog) < 0)
        {
            lg(Fatal, "listen error %d, strerror %s", errno, strerror(errno));
            exit(listenerr);
        }
    }

    int Accept(std::string* ip, uint16_t* port)
    {
        struct sockaddr_in peer;//远端主机的IP，端口等信息
        socklen_t len = sizeof(peer);
        int newfd = accept(_sockfd, (struct sockaddr*)&peer, &len);
        
        *port = ntohs(peer.sin_port);
        char tmpip[64];
        inet_ntop(AF_INET, &peer.sin_addr, tmpip, sizeof(tmpip));
        *ip = tmpip;
        
        return newfd;
    }

    bool Connect(std::string& ip, uint16_t port)
    {
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(port);
        inet_pton(AF_INET, ip.c_str(), &(server.sin_addr));

        int n = connect(_sockfd, (const sockaddr*)&server, sizeof(server));
        if(n < 0)
        {
            std::cerr << "connect error" << std::endl;
            return false;
        }
        return true;
    }

    void Close()
    {
        close(_sockfd);
    }

    int Getfd()
    {
        return _sockfd;
    }

private:
    int _sockfd;
};